/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aeronef.builder;

import aeronef.appStates.GameState;
import aeronef.model.Gun;
import aeronef.model.Turret;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.scene.Spatial;
import java.util.List;
import org.w3c.dom.Element;
import aeronef.model.Ship;
import control.game.TurretTargetingControl;

/**
 *
 * @author Hagan
 */
public class TurretBuilder extends AbstractBuilder {

    GunBuilder gunBuilder;
    ProjectileBuilder projectileBuilder;
    
    Turret turret;
    Spatial turretGeo;
    
    
    
    public TurretBuilder(GameState gameState) {
        super(gameState);
        projectileBuilder = new ProjectileBuilder(gameState);
        gunBuilder = new GunBuilder(gameState, projectileBuilder);
    }

    public Turret buildFromDefinition(String name, String type, Ship ship) {

        String definitionString = (String) assetManager.loadAsset("Data/ships/turrets/" + type + ".xml");
        definition = buildDocument(definitionString);
        
        turret = new Turret(stateManager);
        turret.addControl(new TurretTargetingControl(turret, ship));
        
        buildTurretProperties();
        buildTurretGeometry();
        addGuns();
        
        return turret;
    }

    private void buildTurretProperties() {
       
       turret.setTraverseRate(getTagValueAsFloat("traverseRate", definition.getDocumentElement()));
       turret.setElevateRate(getTagValueAsFloat("elevateRate", definition.getDocumentElement()));
    }
    
    private void buildTurretGeometry() {
        
        String mesh = getTagValue("mesh", definition.getDocumentElement());
        turretGeo = assetManager.loadModel("Models/ships/turrets/" + mesh + ".j3o");
        Material mat = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md"); // default material
        turretGeo.setMaterial(mat);
        turret.attachChild(turretGeo);
    }
  
    private void addGuns() {
        
        List<Gun> guns = turret.getGuns();
        for (Element gunElement : getElementsByTagName(definition.getDocumentElement(), "gun")) {

            String type = getTagValue("type", gunElement);
            Gun gunNode = gunBuilder.buildFromDefinition("-", type);
            guns.add(gunNode);
            turret.attachChild(gunNode);

            //position
            Float xPos = getTagValueAsFloat("xPos", gunElement);
            Float yPos = getTagValueAsFloat("yPos", gunElement);
            Float zPos = getTagValueAsFloat("zPos", gunElement);
            gunNode.move(xPos, yPos, zPos);
        }
    }

}
